﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.SessionState;

namespace BaiTu.SessionServices
{
    public class RedisSessionIDManager : SessionIDManager
    {
        private Random rnd = new Random();
        private object oLock = new object();

        public override string CreateSessionID(System.Web.HttpContext context)
        {
            int index = 0;
            lock (this.oLock)
            {
                index = rnd.Next(SessionConfiguration.SessionServerIdentities.Length);
            }
            string sessionId = string.Format("{0}.{1}", SessionConfiguration.SessionServerIdentities[index], base.CreateSessionID(context));
            return sessionId;
        }

        public override string Encode(string id)
        {
            return Common.Helpers.EncryptHelper.DESEncode(id, Framework.Core.Global.BaiTuGlobal.SessionDESKey);
        }
        public override string Decode(string id)
        {
            return Common.Helpers.EncryptHelper.DESDecode(id, Framework.Core.Global.BaiTuGlobal.SessionDESKey);            
        }

        public override bool Validate(string id)
        {
            string prefix;
            string realId;

            if (!SessionHelper.ParseSessionID(id, out prefix, out realId))
                return false;

            return base.Validate(realId);
        }
    }
}
